package cc.yaomm.service.basic.init;

import cc.yaomm.common.biz.business.BaseInitResource;
import cc.yaomm.common.biz.enums.ServeTypeEnum;
import cc.yaomm.service.basic.service.user.ResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * Created by XQL on 2021/6/9.
 */
@Slf4j
@Component
public class InitResource extends BaseInitResource implements InitializingBean {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Autowired
    private ResourceService resourceService;

    @Override
    public void afterPropertiesSet() {
        CompletableFuture.runAsync(() -> {
            try {
                resourceService.refresh(ServeTypeEnum.BASIC, handlerMapping.getHandlerMethods()
                        .values().stream().map(x -> super.getResources(x, ServeTypeEnum.BASIC))
                        .flatMap(Collection::stream).collect(Collectors.toList()));
            } catch (Exception e) {
                log.error("初始化资源异常", e);
            }
        });
    }
}
